package cn.cloud9.designpattern.dp08flyweight.connection;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Vector;

/**
 * @projectName: Java
 * @author: 戴知舟
 * @date: 2022年05月24日 14:09
 * @version: 1.0
 */
public class ConnectionPool {

    private Vector<Connection> pool;
    private int poolSize = 100;
    private final static String url = "jdbc:mysql://localhost:3308/test";
    private final static String username = "root";
    private final static String password = "123456";
    private final static String driverClassName = "com.mysql.jdbc.Driver";

    public ConnectionPool(int poolSize) {
        this.poolSize = poolSize;
        this.initialize();
    }

    public ConnectionPool() {
        this.initialize();
    }

    private void initialize() {
        this.pool = new Vector<>();

        for (int i = 0; i < this.poolSize; i++) {
            try {
                Class.forName(driverClassName);
                Connection connection = DriverManager.getConnection(url, username, password);
                this.pool.add(connection);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized Connection getConnection() {
        if (pool.size() > 0) {
            Connection connection = pool.get(0);
            pool.remove(connection);
            return connection;
        }
        return null;
    }

    public synchronized void release(Connection connection) {
        pool.add(connection);
    }
}
